package cn.zd.demo1;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContract;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Layout;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

import cn.zd.demo1.util.DisplayUtil;

public class ImageViewActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private static final int R_CODE = 1;
    private final static String originString = "scaleType=fitStart,点我修改";
    private ImageView imageView,iv_dcim;
    private TextView tview,tv_selectdcim,tv_selectpic;
    private ActivityResultLauncher<Intent> resultLauncher;
    private GridLayout gl_img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Toast.makeText(this,this.getClass().getName(),Toast.LENGTH_LONG).show();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imageview);
        imageView = findViewById(R.id.imgview_first);
        iv_dcim = findViewById(R.id.iv_dcim);
        tview = findViewById(R.id.tv_first);
        tview.setOnClickListener(this);
        tv_selectdcim = findViewById(R.id.tv_selectdcim);
        gl_img = findViewById(R.id.gl_img);
        tv_selectdcim.setOnClickListener(this);
        tv_selectpic = findViewById(R.id.tv_selectpic);
        tv_selectpic.setOnClickListener(this);
        resultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
            @Override
            public void onActivityResult(ActivityResult result) {
                if(result.getResultCode() ==  RESULT_OK) {
                    Intent intent = result.getData();
                    Uri picUrl = intent.getData();
                    if(picUrl != null) {
                        iv_dcim.setImageURI(picUrl);
                    }else {
                        Toast.makeText(ImageViewActivity.this,"未选择任何图片",Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @SuppressLint("Range")
    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.tv_first) {
            int i = new Random().nextInt(7);
            ImageView.ScaleType type = ImageView.ScaleType.values()[i];
            tview.setText(originString + ":" + type.name());
            imageView.setScaleType(type);
        } else if(v.getId() == R.id.tv_selectdcim) {
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            resultLauncher.launch(intent);
        } else if(v.getId() == R.id.tv_selectpic) {
            if((ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED)) {
                Toast.makeText(this,"需要授权",Toast.LENGTH_SHORT).show();
                ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, R_CODE);
                return;
            }
            List<Object[]> images = new ArrayList<>();
            Cursor pics = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[]{MediaStore.Images.Media._ID, MediaStore.Images.Media.TITLE, MediaStore.Images.Media.SIZE, MediaStore.Images.Media.DATA}, "_size<1048567", null, "_size DESC");
            while (pics.moveToNext() && images.size() < 10) {
                Object[] data = new Object[4];
                data[0] = pics.getLong(pics.getColumnIndex(MediaStore.Images.Media._ID));
                data[1] = pics.getLong(pics.getColumnIndex(MediaStore.Images.Media.SIZE));
                data[2] = pics.getString(pics.getColumnIndex(MediaStore.Images.Media.TITLE));
                data[3] = pics.getString(pics.getColumnIndex(MediaStore.Images.Media.DATA));
                images.add(data);
            }
            pics.close();
            gl_img.removeAllViews();
            images.forEach(imgs -> {
                ImageView iv = new ImageView(this);
                iv.setImageBitmap(BitmapFactory.decodeFile((String) imgs[3]));
                iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
                int px = DisplayUtil.dp2px(this, 200);
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(px,px);
                gl_img.addView(iv);
            });

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == R_CODE) {
            Button btn = null;
            tv_selectpic.callOnClick();
        }
    }
}